<?php
namespace app\api\service;

use app\common\library\wechat\WxSubMsg;
use app\common\service\BaseService;

/**
 * 推送模板消息服务类
 * Class Message
 * @package app\store\service\wxapp
 */
class Message extends BaseService
{
    // 分割符号
    const SEPARATOR = ',';

    /** @var array $stateSet 状态集 */
    private $stateSet = [];

    /** @var WxTplMsg $WxTplMsg 微信模板消息类 */
    private $WxSubMsg;

    /**
     * 构造方法
     * Message constructor.
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function __construct()
    {
        // 实例化：微信模板消息类

        $app_id         = 'wx08aa30abf9a73c17';
        $app_secret     = '3e7a0d5b7b8417dd9353ca7741f6e4de';
        $this->WxSubMsg = new WxSubMsg($app_id, $app_secret);
    }

    /**
     * @param $data
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function send($open_id, $data)
    {

        $this->sendTemplateMessage($open_id, $data);
        return true;
    }

    /**
     * 发送模板消息
     * @param $userId
     * @param $data
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    private function sendTemplateMessage($open_id, $data)
    {

        $params = [
            'touser'      => $open_id,
            'template_id' => $data['template_id'],
            'page'        => $data['page'],
            'data'        => $data['data'],
            
    //          'data' => [
    //     'keyword1' => ['value' => '示例内容1'],
    //     'keyword2' => ['value' => '示例内容2']
    // ]
        ];

        $result = $this->WxSubMsg->sendTemplateMessage($params);
        //print_r($result);exit;
        // 请求微信api：发送模板消息
        // if ($status = $this->WxTplMsg->sendTemplateMessage($params)) {
        // 	$this->recordState("发送成功！");
        // }

        return true;
    }

}
